package cn.myframe.controller.sys;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.myframe.controller.AbstractController;
import cn.myframe.entity.bus.BusCompanyEntity;
import cn.myframe.entity.sys.SysInfoCompanyEntity;
import cn.myframe.entity.sys.SysInfoEntity;
import cn.myframe.entity.sys.SysInfoUserEntity;
import cn.myframe.service.bus.BusCompanyService;
import cn.myframe.service.sys.SysInfoCompanyService;
import cn.myframe.service.sys.SysInfoService;
import cn.myframe.service.sys.SysInfoUserService;
import cn.myframe.service.sys.SysUserService;
import cn.myframe.utils.core.PageUtils;
import cn.myframe.utils.core.Query;
import cn.myframe.utils.core.R;
import cn.myframe.utils.annotation.IgnoreAuth;
import cn.myframe.utils.annotation.SysLog;


/**
 * 消息列表; InnoDB free: 3431424 kB
 * 
 * @author ynz
 * @email ynz@myframe.cn
 * @date 2017-09-07 15:18:56
 */
@RestController
@RequestMapping("/sys/sysinfo")
public class SysInfoController  extends AbstractController{
	@Autowired
	private SysInfoService sysInfoService;
	
	@Autowired
	private SysInfoCompanyService sysInfoCompanyService;
	
	@Autowired
	private SysInfoUserService sysInfoUserService;
	
	@Autowired
	private BusCompanyService busCompanyService;
	
	@Autowired
	private SysUserService sysUserService;
	
	public static final int ADMIN = 1;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	//@RequiresPermissions("sysinfo:list")
	public R list(@RequestParam Map<String, Object> params){
	    //doBefore(params, "sysinfo:list");	
		//查询列表数据
	    params.put("userId", getUserId());
        Query query =null;
        List<SysInfoEntity> sysInfoList = null;  
        int total=0;
        if(params.get("infoStatus")!=null&&params.get("infoStatus")!=""){
        	int infoStatus = Integer.parseInt(String.valueOf(params.get("infoStatus")));
        	if(infoStatus==0){
        		params.put("infoStatus", "wd");
        	}else{
        		params.put("infoStatus", "yd");
        	}
        }
        if(getUser().getType()!= null && getUser().getType() ==ADMIN){
           query = new Query(params);           
           sysInfoList = sysInfoService.queryList(query);
           total = sysInfoService.queryTotal(query);
        }else{
        	params.put("companyId", getUser().getCompanyNo());
        	query = new Query(params);   
        	sysInfoList = sysInfoService.queryInfoList(query);
        	total = sysInfoService.queryUserTotal(query);
        }		
		PageUtils pageUtil = null;
		pageUtil = new PageUtils(sysInfoList, total, query.getLimit(), query.getPage());
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 获取用户未读消息条数
	 */
	@RequestMapping(value = "/infoCount")
	@IgnoreAuth
	public R getMessageCount(){
		int infoCount=0;
        if(getUser().getType()!= null && getUser().getType() == ADMIN){
        	infoCount = sysInfoService.queryAdminInfoCount(getUserId());
        }else{
		  List<Long> list =	sysUserService.queryDataUser(getUser().getUserId(), "sysinfo:list", null);
		  List<Long> listSon = sysUserService.queryUserBySonCompany(getUser().getCompanyNo());
		  if(listSon != null){
			  list.addAll(listSon);
		  }	
   		  infoCount = sysInfoService.queryInfoCount(getUserId(),getUser().getCompanyNo(),list);
        }
		return R.ok().put("msgCount", infoCount);
		
	}

	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sysinfo:info")
	public R info(@PathVariable("id") String id){
		int isRead = sysInfoUserService.queryByInfoId(Long.valueOf(id),getUserId());
		if(isRead==0){
			SysInfoUserEntity sysInfoUserEntity = new SysInfoUserEntity();
			sysInfoUserEntity.setInfoId(Long.valueOf(id));
			sysInfoUserEntity.setUserId(getUserId());
			sysInfoUserService.save(sysInfoUserEntity);
		}
		SysInfoEntity sysInfo = sysInfoService.queryObject(Long.valueOf(id));
		
		return R.ok().put("sysInfo", sysInfo);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sysinfo:save")
	@Transactional
	@SysLog("logSaveData")
	public R save(@RequestBody SysInfoEntity sysInfo){
		sysInfo.setCreateBy(getUserId());
		sysInfo.setCreateTime(new Date());
		sysInfo.setStatus(0);
		sysInfoService.save(sysInfo);
		String sysInfoId = sysInfo.getId();
		if(sysInfo.getBusCompanyIdList()!=null&&sysInfo.getBusCompanyIdList().size()>0){
			for(Integer busCompanyId : sysInfo.getBusCompanyIdList()){
				SysInfoCompanyEntity map = new SysInfoCompanyEntity();
				map.setCompanyId(Long.valueOf(busCompanyId));
				map.setInfoId(Long.valueOf(sysInfoId));
				sysInfoCompanyService.save(map);
			}
		}
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sysinfo:update")
	@Transactional
	@SysLog("logUpateData")
	public R update(@RequestBody SysInfoEntity sysInfo){
		sysInfoService.update(sysInfo);
		String sysInfoId = sysInfo.getId();
		sysInfoCompanyService.deleteByInfoId(Long.valueOf(sysInfoId));

		if(sysInfo.getBusCompanyIdList()!=null&&sysInfo.getBusCompanyIdList().size()>0){
			for(Integer busCompanyId : sysInfo.getBusCompanyIdList()){
				SysInfoCompanyEntity map = new SysInfoCompanyEntity();
				map.setCompanyId(Long.valueOf(busCompanyId));
				map.setInfoId(Long.valueOf(sysInfoId));
				sysInfoCompanyService.save(map);
			}
		}
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sysinfo:delete")
	@Transactional
	@SysLog("logDelData")
	public R delete(@RequestBody Long[] ids){
		if(getUser().getType()!= null && getUser().getType() ==ADMIN){
			sysInfoService.deleteBatch(ids);
			sysInfoUserService.deleteByInfoId(ids);
			sysInfoCompanyService.deleteByInfoIds(ids);
		}else{
			List<SysInfoEntity> sysInfoLists = sysInfoService.selectSysInfos(ids);			
			List<Long> parentIds =  busCompanyService.queryParentCompany(getUser().getCompanyNo());
			for(SysInfoEntity sysInfoEntity:sysInfoLists){
				BusCompanyEntity busCompanyEntity = busCompanyService.queryObject(sysInfoEntity.getCreator().getCompanyNo());
				for(Long parentId:parentIds){
					if(parentId==busCompanyEntity.getCompanyNo()){
						 return R.error("下级不能删除上级的信息");
					}
				}
			}
			sysInfoService.deleteBatch(ids);
			sysInfoUserService.deleteByInfoId(ids);
			sysInfoCompanyService.deleteByInfoIds(ids);		
		}
		
		

		return R.ok();
	}
	
    /**
     * 检验字段名是否存在重复
     */
    @RequestMapping("/checkExist")
    @ResponseBody
    public String checkExist(String id,String name){
        boolean result = true;
        int count = sysInfoService.checkExist(id, name);
        if(count > 0 ){
            result = false;
        }
        return "{\"valid\":" + result + "}";
    }
    
     /**
     * 提交，审核
     */
    @RequestMapping("/audit")
    @SysLog("logUpateStatus")
    public R audit(@RequestBody Long[] ids ,@RequestParam Integer status){      
    	sysInfoService.updateStatus(ids , status);
        return R.ok();
    }
	
}
